from rich.console import Console
from rich.layout import Layout
from rich.panel import Panel
from rich.live import Live
from rich.text import Text
import psutil
import time

console = Console()


def generate_layout() -> Layout:
    layout = Layout()
    layout.split(
        Layout(name="header", size=3),
        Layout(name="main"),
        Layout(name="footer", size=3)
    )
    layout["main"].split_row(
        Layout(name="left"),
        Layout(name="right")
    )
    return layout


def get_cpu_usage() -> Panel:
    cpu_percent = psutil.cpu_percent(interval=1)
    cpu_count = psutil.cpu_count()

    cpu_text = Text()
    cpu_text.append(f"核心数: {cpu_count}\n", style="bold cyan")

    for i, percent in enumerate(psutil.cpu_percent(interval=1, percpu=True)):
        cpu_text.append(f"核心 {i}: ")
        bar = "█" * int(percent / 5) + " " * (20 - int(percent / 5))
        cpu_text.append(bar, style="red" if percent > 80 else "yellow" if percent > 50 else "green")
        cpu_text.append(f" {percent:.1f}%\n")

    return Panel(
        cpu_text,
        title="CPU 使用率",
        border_style="bright_blue"
    )


def get_memory_usage() -> Panel:
    mem = psutil.virtual_memory()
    swap = psutil.swap_memory()

    memory_text = Text()
    memory_text.append(f"物理内存: {mem.percent}%\n", style="bold")
    memory_text.append(f"已用: {mem.used / (1024 ** 3):.1f} GB / {mem.total / (1024 ** 3):.1f} GB\n")

    bar_length = 30
    used_blocks = int(mem.percent / 100 * bar_length)
    memory_text.append("[" + "█" * used_blocks + " " * (bar_length - used_blocks) + "]\n")

    memory_text.append(f"\n交换空间: {swap.percent}%\n", style="bold")
    memory_text.append(f"已用: {swap.used / (1024 ** 3):.1f} GB / {swap.total / (1024 ** 3):.1f} GB")

    return Panel(
        memory_text,
        title="内存使用情况",
        border_style="bright_blue"
    )


def update_dashboard() -> Layout:
    layout = generate_layout()
    layout["header"].update(
        Panel("系统监控仪表盘", style="bold white on blue")
    )
    layout["left"].update(get_cpu_usage())
    layout["right"].update(get_memory_usage())
    layout["footer"].update(
        Panel(f"更新时间: {time.strftime('%Y-%m-%d %H:%M:%S')}", style="dim")
    )
    return layout


try:
    with Live(update_dashboard(), refresh_per_second=4) as live:
        while True:
            live.update(update_dashboard())
            time.sleep(0.5)
except KeyboardInterrupt:
    console.print("[red]监控已停止[/red]")